<template>
  <div>
    <el-card class="box-card">

      <el-form :model="book" :rules="rules" ref="bookForm" label-width="120px">
        <el-form-item label="书籍名称" prop="title">
          <el-input v-model="book.title"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="book.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="book.publisher"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker v-model="book.publishDate" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="book.category"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="totalCopies">
          <el-input v-model="book.totalCopies" type="number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('bookForm')">入库</el-button>
          <el-button @click="resetForm('bookForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '../../utils/request';

export default {
  name: 'AddBook',
  data() {
    return {
      book: {
        title: '',
        author: '',
        publisher: '',
        publishDate: '',
        category: '',
        totalCopies: 0
      },
      rules: {
        title: [{ required: true, message: '请输入书籍名称', trigger: 'blur' }],
        author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
        publisher: [{ required: true, message: '请输入出版社', trigger: 'blur' }],
        publishDate: [{ required: true, message: '请选择出版日期', trigger: 'change' }],
        category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
        totalCopies: [{ required: true, message: '请输入数量', trigger: 'blur' }]
      }
    };
  },
  methods: {
    save(){

    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          request.post('/book/addBook', this.book) //请求后端方法
              .then(res => {
                if(res.code == '200'){
                  this.$message.success('书籍添加成功');
                  this.resetForm(formName);
                }
              })
              .catch(error => {
                console.error('Error adding book:', error);
                this.$message.error('书籍添加失败');
              });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
</style>